import datetime
from django.shortcuts import render, HttpResponse

from app01.tasks import add, mul
from celery.result import AsyncResult
from celeryPro.celery import app


def celery1(request):
    """
    立即执行的celery定时任务
    :param request:
    :return:
    """
    result = add.delay(100, 88)
    result_object = AsyncResult(id=result.id, app=app)
    print('result_object.status=====> ', result_object.status)
    # if result_object.status == "SUCCESS":
    data = result_object.get()
    return HttpResponse(data)
    # return HttpResponse('error..')

def celery2(request):
    """
    间隔1分钟后执行的celery任务
    PS:需要拿着任务ID去查询结果
        get/result/?nid=任务id查询结果
    :param request:
    :return:
    """
    ctime = datetime.datetime.now()
    utc_ctime = datetime.datetime.utcfromtimestamp(ctime.timestamp())

    s60 = datetime.timedelta(seconds=60)
    ctime_x = utc_ctime + s60

    result = add.apply_async(args=[1000, 888], eta=ctime_x)
    return HttpResponse(result.id)


def get_result(request):
    nid = request.GET.get('nid')
    result_object = AsyncResult(id=nid, app=app)
    if result_object.status == 'SUCCESS':
        data = result_object.get()
        return HttpResponse(data)
    return HttpResponse('任务正在执行中..')
